package com.fatmeraid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.login.LoginUser;
import com.fatmeraid.common.login.LoginUserHolder;
import com.fatmeraid.common.model.PageResult;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.dao.OrderDao;
import com.fatmeraid.dao.ProductDao;
import com.fatmeraid.dao.UserDao;
import com.fatmeraid.domain.Order;
import com.fatmeraid.domain.Product;
import com.fatmeraid.service.OrderService;
import com.fatmeraid.vo.order.AddOrderVo;
import com.fatmeraid.vo.order.GetOrderVo;
import com.fatmeraid.vo.order.UpdateOrderVo;
import com.fatmeraid.vo.order.UpdateStatusVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderDao orderDao;

	@Autowired
	private ProductDao productDao;

	@Autowired
	private UserDao userDao;

	// 添加订单
	@Override
	public Long addOrder(AddOrderVo addOrderVo) {
		// 1. 参数校验
		if (addOrderVo == null) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR);
		}
		// 校验必填字段
		if (addOrderVo.getProductId() == null || addOrderVo.getQuantity() == null) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR.getCode(), "订单参数不完整");
		}
		if (addOrderVo.getQuantity() <= 0) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR.getCode(), "购买数量必须大于0");
		}

		// 校验收货信息
		if (!StringUtils.hasText(addOrderVo.getShippingAddress())
				|| !StringUtils.hasText(addOrderVo.getReceiptName())
				|| !StringUtils.hasText(addOrderVo.getReceiptPhone())) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR.getCode(), "收货信息不完整");
		}

		// 2. 获取当前登录用户信息（购买者）
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();

		// 3. 查询产品信息，检查库存
		Product product = productDao.selectById(addOrderVo.getProductId());
		if (product == null) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "商品不存在");
		}

		// 检查商品是否上架
		if (product.getStatus() != 2) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "商品未上架或已下架");
		}

		// 检查库存是否足够
		if (product.getStock() < addOrderVo.getQuantity()) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "库存不足");
		}


		// 4. 创建订单对象
		Order order = new Order();
		order.setUserId(userId); // 购买用户ID
		order.setFarmerId(product.getFarmerId()); // 农户ID
		order.setProductId(addOrderVo.getProductId()); // 产品ID
		order.setProductName(product.getProductName()); // 商品名称
		order.setQuantity(addOrderVo.getQuantity()); // 购买数量
		order.setUnitPrice(product.getPrice()); // 购买单价
		order.setTotalPrice(product.getPrice() * addOrderVo.getQuantity()); // 总价
		order.setShippingAddress(addOrderVo.getShippingAddress()); // 收货地址
		order.setReceiptName(addOrderVo.getReceiptName()); // 收货人姓名
		order.setReceiptPhone(addOrderVo.getReceiptPhone()); // 收货人电话

		// 5. 保存订单
		int insertResult = orderDao.insert(order);
		if (insertResult <= 0) {
			throw new FarmException(ResultCodeEnum.FAIL);
		}

		// 6. 更新产品库存
		LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(Product::getProductId, addOrderVo.getProductId())
				.set(Product::getStock, product.getStock() - addOrderVo.getQuantity());

		int updateResult = productDao.update(null, updateWrapper);

		// System.out.println("orderId:" + order.getOrderId());
		if (updateResult <= 0 ){
			throw new FarmException(ResultCodeEnum.FAIL);
		}
		return order.getOrderId();
	}

	// 获取订单列表
	@Override
	public PageResult<Order> getOrderList(GetOrderVo getOrderVo) {
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		// 获取当前登录用户角色
		Integer roleType = userDao.selectById(userId).getRoleType();

		// 创建分页对象
		IPage<Order> page = new Page<>(getOrderVo.getCurrent(), getOrderVo.getSize());

		// 创建查询条件
		LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();


		// 根据用户角色构建查询条件
		if (roleType.equals(3)) {
			// 管理员可以查看所有订单
		} else if (roleType.equals(2)) {
			// 农户只能查看购买了自己商品的订单
			queryWrapper.eq(Order::getFarmerId, userId);
		} else {
			// 普通用户只能查看自己购买的订单
			queryWrapper.eq(Order::getUserId, userId);
		}


		IPage<Order> orders = orderDao.selectPage(page, queryWrapper);

		// 批量查询商品名称
		List<Order> orderList = orders.getRecords();
		if (!orderList.isEmpty()) {
			Set<Long> productIds = orderList.stream()
					.map(Order::getProductId)
					.collect(Collectors.toSet());

			LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
			productQueryWrapper.in(Product::getProductId, productIds);
			productQueryWrapper.select(Product::getProductId, Product::getProductName);

			List<Product> products = productDao.selectList(productQueryWrapper);
			Map<Long, String> productNameMap = products.stream()
					.collect(Collectors.toMap(Product::getProductId, Product::getProductName));

			// 设置商品名称
			orderList.forEach(order -> {
				order.setProductName(productNameMap.get(order.getProductId()));
			});
		}

		return new PageResult<>(orders.getTotal(), orders.getRecords());
	}



	// 获取订单详情
	@Override
	public Order getOrderDetail(Long orderId) {
		Order order = orderDao.selectById(orderId);
		Long productId = order.getProductId();
		String productName = productDao.selectById(productId).getProductName();
		order.setProductName(productName);
		return order;
	}

	// 修改订单收货信息
	@Override
	public boolean updateOrder(UpdateOrderVo updateOrderVo) {
		// 1. 参数校验
		if (updateOrderVo == null) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR);
		}
		// 校验必填字段
		if (updateOrderVo.getOrderId() == null) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR.getCode(), "订单ID不能为空");
		}

		// 2. 获取当前登录用户信息
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();

		// 3. 查询订单信息
		Order order = orderDao.selectById(updateOrderVo.getOrderId());
		if (order == null) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "订单不存在");
		}

		// 4. 检查是否有权限修改该订单（只能修改自己的订单）
		if (!order.getUserId().equals(userId)) {
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		// 5. 检查订单状态是否为未发货状态（0-待付款或1-待发货）
		Integer status = order.getStatus();
		if (status != 0 && status != 1) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "订单已发货，无法修改收货信息");
		}

		// 6. 创建更新条件
		LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(Order::getOrderId, updateOrderVo.getOrderId());

		// 7. 设置需要更新的收货信息
		if (StringUtils.hasText(updateOrderVo.getShippingAddress())) {
			updateWrapper.set(Order::getShippingAddress, updateOrderVo.getShippingAddress());
		}
		if (StringUtils.hasText(updateOrderVo.getReceiptName())) {
			updateWrapper.set(Order::getReceiptName, updateOrderVo.getReceiptName());
		}
		if (StringUtils.hasText(updateOrderVo.getReceiptPhone())) {
			updateWrapper.set(Order::getReceiptPhone, updateOrderVo.getReceiptPhone());
		}

		// 8. 执行更新操作
		int updateResult = orderDao.update(null, updateWrapper);

		return updateResult > 0;
	}

	// 修改订单状态
	@Override
	public boolean updateOrderStatus(UpdateStatusVo updateStatusVo) {
		// 1. 参数校验
		if (updateStatusVo == null) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR);
		}
		if (updateStatusVo.getOrderId() == null || updateStatusVo.getStatus() == null) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR.getCode(), "订单ID和状态不能为空");
		}

		// 2. 获取当前登录用户信息和角色
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		Integer roleType = userDao.selectById(userId).getStatus();

		// 3. 查询订单信息
		Order order = orderDao.selectById(updateStatusVo.getOrderId());
		if (order == null) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "订单不存在");
		}

		// 4. 检查权限和状态转换的合理性
		Integer currentStatus = order.getStatus();
		Integer targetStatus = updateStatusVo.getStatus();

		// 普通用户（roleType=1）只能从待支付（0）改成取消（4）或从已发货（2）改成确认收货（3）
		if (roleType.equals(1)) {
			if (!userId.equals(order.getUserId())) {
				throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
			}
			if (!((currentStatus == 0 && targetStatus == 4) || (currentStatus == 2 && targetStatus == 3))) {
				throw new FarmException(ResultCodeEnum.FAIL);
			}
		}
		// 农户（roleType=2）可以把待发货（1）改成已发货（2）
		else if (roleType.equals(2)) {
			if (!userId.equals(order.getFarmerId())) {
				throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
			}
			if (currentStatus != 1 || targetStatus != 2) {
				throw new FarmException(ResultCodeEnum.FAIL);
			}
		}


		// 5. 创建更新条件
		LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(Order::getOrderId, updateStatusVo.getOrderId())
				.set(Order::getStatus, targetStatus);

		// 6. 根据目标状态设置相应时间
		if (targetStatus == 2) {
			// 已发货状态，设置发货时间
			updateWrapper.set(Order::getDeliveryTime, LocalDateTime.now());
		} else if (targetStatus == 3) {
			// 确认收货状态，更新销量
			Product product = productDao.selectById(order.getProductId());
			LambdaUpdateWrapper<Product> productUpdateWrapper = new LambdaUpdateWrapper<>();
			productUpdateWrapper.eq(Product::getProductId, order.getProductId())
					.set(Product::getSalesVolume,product.getSalesVolume() + order.getQuantity() );
			// 确认收货状态，设置收货时间
			updateWrapper.set(Order::getReceiptTime, LocalDateTime.now());
		}

		// 7. 如果是取消订单，返还库存
		if (targetStatus == 4) {
			Product product = productDao.selectById(order.getProductId());
			if (product != null) {
				LambdaUpdateWrapper<Product> productUpdateWrapper = new LambdaUpdateWrapper<>();
				productUpdateWrapper.eq(Product::getProductId, order.getProductId())
						.set(Product::getStock, product.getStock() + order.getQuantity());
				productDao.update(null, productUpdateWrapper);
			}
		}

		// 8. 执行订单状态更新操作
		int updateResult = orderDao.update(null, updateWrapper);

		return updateResult > 0;
	}


	// 删除订单
	@Override
	public boolean deleteOrder(String orderId) {
		// 1. 参数校验
		if (orderId == null) {
			throw new FarmException(ResultCodeEnum.PARAM_ERROR.getCode(), "订单ID不能为空");
		}

		// 2. 获取当前登录用户信息
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		Integer roleType = userDao.selectById(userId).getStatus();

		// 3. 查询订单信息
		Order order = orderDao.selectById(orderId);
		if (order == null) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "订单不存在");
		}

		// 4. 检查是否有权限删除该订单
		// 管理员可以删除任何订单
		// 普通用户只能删除自己的订单
		// 农户只能删除自己相关的订单
		if (roleType.equals(1)) {
			// 普通用户
			if (!userId.equals(order.getUserId())) {
				throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
			}
		} else if (roleType.equals(2)) {
			// 农户
			if (!userId.equals(order.getFarmerId())) {
				throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
			}
		}
		// 管理员(roleType=3)不需要额外的权限检查

		// 5. 检查订单状态是否为已取消(4)或已确认收货(3)
		Integer status = order.getStatus();
		if (status != 3 && status != 4) {
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "只能删除已取消或已确认收货的订单");
		}

		// 6. 执行删除操作
		int deleteResult = orderDao.deleteById(orderId);

		return deleteResult > 0;
	}

	@Override
	public boolean updateOrderStatus(String tradeNo, String gmtPayment, String alipayTradeNo) {
		LambdaUpdateWrapper<Order> luw = new LambdaUpdateWrapper<>();
		luw.eq(Order::getOrderId, tradeNo); // 订单ID
		luw.set(Order::getStatus, 1);// 待发货
		luw.set(Order::getPaymentTime, gmtPayment); // 支付时间
		luw.set(Order::getTransactionId, alipayTradeNo); // 交易编号
		int ret = orderDao.update(null, luw);
		return ret > 0;
	}

	@Override
	public PageResult<Order> getMyOrder(GetOrderVo getOrderVo) {
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();

		// 创建分页对象
		IPage<Order> page = new Page<>(getOrderVo.getCurrent(), getOrderVo.getSize());

		// 创建查询条件
		LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Order::getUserId, userId);

		IPage<Order> orders = orderDao.selectPage(page, queryWrapper);

		// 批量查询商品名称
		List<Order> orderList = orders.getRecords();
		if (!orderList.isEmpty()) {
			Set<Long> productIds = orderList.stream()
					.map(Order::getProductId)
					.collect(Collectors.toSet());

			LambdaQueryWrapper<Product> productQueryWrapper = new LambdaQueryWrapper<>();
			productQueryWrapper.in(Product::getProductId, productIds);
			productQueryWrapper.select(Product::getProductId, Product::getProductName);

			List<Product> products = productDao.selectList(productQueryWrapper);
			Map<Long, String> productNameMap = products.stream()
					.collect(Collectors.toMap(Product::getProductId, Product::getProductName));

			// 设置商品名称
			orderList.forEach(order -> {
				order.setProductName(productNameMap.get(order.getProductId()));
			});
		}

		return new PageResult<>(orders.getTotal(), orders.getRecords());
	}
}

